/**
 * 
 */
package xj.toolkit.netty.handler.codec.http.response;

import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;

/**
 * @author hp
 *
 */
public class NettyHttpResponseBuilder {

	/**
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @see com.skymobi.http.HttpResponseBuilder#build(org.apache.asyncweb.common
	 *      .HttpRequest, java.lang.Object)
	 */
	public static HttpResponse build(Object source)
			throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		FullHttpResponse resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);

		resp.setStatus((HttpResponseStatus) PropertyUtils.getProperty(source, "status"));

		String contentType = BeanUtils.getProperty(source, "contentType");
		if (null != contentType) {
			resp.headers().set(HttpHeaders.Names.CONTENT_TYPE, contentType);
		}

		byte[] bytes = (byte[]) PropertyUtils.getProperty(source, "content");
		if (null != bytes) {
			resp.content().writeBytes(bytes);
		}

		String contentLength = BeanUtils.getProperty(source, "contentLength");
		if (null != contentLength && !contentLength.equals("0")) {
			resp.headers().set(HttpHeaders.Names.CONTENT_LENGTH, contentLength);
		} else {
			resp.headers().set(HttpHeaders.Names.CONTENT_LENGTH, bytes == null ? 0 : bytes.length);
		}

		String contentRange = BeanUtils.getProperty(source, "contentRange");
		if (null != contentRange) {
			resp.headers().set("Content-Range", contentRange);
		}
		String date = BeanUtils.getProperty(source, "date");
		if (null != date) {
			resp.headers().set("Date", date);
		}

		return resp;
	}

}
